
package com.zzjc.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


public class MaptoEntityUtil {
    public final static Logger logger = LoggerFactory.getLogger(MaptoEntityUtil.class);

    private static SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat simpleDateFormate2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");



    public static <T> T mapToBean(Map<String, Object> map, Class<?> clazz) throws Exception {
        Object obj = clazz.newInstance();
        if (map != null && !map.isEmpty() && map.size() > 0) {
            for (Entry<String, Object> entry : map.entrySet()) {
                String propertyName = entry.getKey();    // 属性名
                Object value = entry.getValue();        // 属性值
                if (null == value || StringKit.isBlank(String.valueOf(value)))
                    continue;
                String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                Field field = getClassField(clazz, propertyName);    //获取和map的key匹配的属性名称
                if (field == null) {
                    continue;
                }
                Class<?> fieldTypeClass = field.getType();
                value = convertValType(value, fieldTypeClass);
                try {
                    if (StringKit.notBlank(setMethodName) && setMethodName.toUpperCase().contains("SERIALVERSIONUID"))
                        continue;
                    if (field.getType() == BigDecimal.class) {
                        clazz.getMethod(setMethodName, field.getType()).invoke(obj, new BigDecimal((value.toString())));
                    } else if (field.getType() == Short.class) {
                        clazz.getMethod(setMethodName, field.getType()).invoke(obj, new Short((value.toString())));
                    } else if (field.getType() == Integer.class) {
                        clazz.getMethod(setMethodName, field.getType()).invoke(obj, new Integer((value.toString())));
                    } else if (field.getType() == Date.class) {
                        clazz.getMethod(setMethodName, field.getType()).invoke(obj, Date.from(LocalDateTime.parse(String.valueOf(value), dateTimeFormatter).toInstant(ZoneOffset.of("+8"))));
                    } else {
//                        setBridgeId(String)
//                        obj.setBridgeId(value)
//                        obj.setUpdateBy(value)
                        clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
        return (T) obj;
    }


    private static Field getClassField(Class<?> clazz, String fieldName) {
        if (Object.class.getName().equals(clazz.getName())) {
            return null;
        }
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        Class<?> superClass = clazz.getSuperclass();    //如果该类还有父类，将父类对象中的字段也取出
        if (superClass != null) {                        //递归获取
            return getClassField(superClass, fieldName);
        }
        return null;
    }


    private static Object convertValType(Object value, Class<?> fieldTypeClass) {
        Object retVal = null;

        if (Long.class.getName().equals(fieldTypeClass.getName())
                || long.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Long.parseLong(value.toString());
        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
                || int.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Integer.parseInt(value.toString());
        } else if (Float.class.getName().equals(fieldTypeClass.getName())
                || float.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Float.parseFloat(value.toString());
        } else if (Double.class.getName().equals(fieldTypeClass.getName())
                || double.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Double.parseDouble(value.toString());
        } else {
            retVal = value;
        }
        return retVal;
    }

    public static Map<String, String> objToMap(Object obj) {

        Map<String, String> map = new HashMap<String, String>();
        Field[] fields = obj.getClass().getDeclaredFields();    // 获取f对象对应类中的所有属性域
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            //varName = varName.toLowerCase();					// 将key置为小写，默认为对象的属性
            try {
                boolean accessFlag = fields[i].isAccessible();    // 获取原来的访问控制权限
                fields[i].setAccessible(true);                    // 修改访问控制权限
                Object o = fields[i].get(obj);                    // 获取在对象f中属性fields[i]对应的对象中的变量
                if (o != null) {
                    map.put(varName, o.toString());
                }
                fields[i].setAccessible(accessFlag);            // 恢复访问控制权限
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
        return map;
    }


    public static HashMap<String, Object> mapStringToHashMapObj(Map<String, String> map) {
        HashMap<String, Object> resultMap = new HashMap<>();
        for (Entry<String, String> entry : map.entrySet()) {
            resultMap.put(entry.getKey(), entry.getValue());
        }
        return resultMap;
    }


    public static HashMap<String, String> mapObjToHashMapStr(Map<String, Object> map) {
        HashMap<String, String> resultMap = new HashMap<>();
        for (Entry<String, Object> entry : map.entrySet()) {
            resultMap.put(entry.getKey(), entry.getValue().toString());
        }
        return resultMap;
    }


    public static Map<String, Field> getDeclaredFieldsMap(Class<?> clazz) {
        Map<String, Field> filesMap = new HashMap<>();
        if (clazz != null) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field f : fields) {
                filesMap.put(f.getName(), f);
            }
        }
        return filesMap;
    }

}
